<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../../includes/config.php';
require_once '../../includes/auth.php';

// 验证登录
$admin = verifyAdminToken();
if (!$admin) {
    http_response_code(401);
    echo json_encode(['code' => 401, 'message' => '未登录或登录已过期']);
    exit;
}

$action = $_GET['action'] ?? '';

switch ($action) {
    case 'list':
        getTimeSlots();
        break;
    case 'add':
        addTimeSlot();
        break;
    case 'update':
        updateTimeSlot();
        break;
    case 'delete':
        deleteTimeSlot();
        break;
    case 'toggle_status':
        toggleStatus();
        break;
    default:
        http_response_code(400);
        echo json_encode(['code' => 400, 'message' => '无效的操作']);
        break;
}

function getTimeSlots() {
    try {
        $stmt = $GLOBALS['pdo']->prepare("
            SELECT id, slot_name, start_time, end_time, max_visitors, sort_order, is_active, 
                   created_at, updated_at
            FROM museum_time_slots 
            ORDER BY sort_order ASC, start_time ASC
        ");
        $stmt->execute();
        $timeslots = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'code' => 200,
            'message' => '获取成功',
            'data' => $timeslots
        ]);
    } catch (Exception $e) {
        echo json_encode(['code' => 500, 'message' => '获取时段失败: ' . $e->getMessage()]);
    }
}

function addTimeSlot() {
    // 检查权限
    if (!hasPermission('timeslots.edit')) {
        echo json_encode(['code' => 403, 'message' => '权限不足']);
        return;
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['slot_name'], $input['start_time'], $input['end_time'], $input['max_visitors'])) {
        echo json_encode(['code' => 400, 'message' => '参数错误']);
        return;
    }
    
    try {
        $stmt = $GLOBALS['pdo']->prepare("
            INSERT INTO museum_time_slots (slot_name, start_time, end_time, max_visitors, sort_order, is_active) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $input['slot_name'],
            $input['start_time'],
            $input['end_time'],
            $input['max_visitors'],
            $input['sort_order'] ?? 1,
            $input['is_active'] ?? 1
        ]);
        
        echo json_encode([
            'code' => 200,
            'message' => '时段添加成功',
            'data' => ['id' => $GLOBALS['pdo']->lastInsertId()]
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['code' => 500, 'message' => '添加时段失败: ' . $e->getMessage()]);
    }
}

function updateTimeSlot() {
    // 检查权限
    if (!hasPermission('timeslots.edit')) {
        echo json_encode(['code' => 403, 'message' => '权限不足']);
        return;
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['id'], $input['slot_name'], $input['start_time'], $input['end_time'], $input['max_visitors'])) {
        echo json_encode(['code' => 400, 'message' => '参数错误']);
        return;
    }
    
    try {
        $stmt = $GLOBALS['pdo']->prepare("
            UPDATE museum_time_slots 
            SET slot_name = ?, start_time = ?, end_time = ?, max_visitors = ?, 
                sort_order = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ");
        $stmt->execute([
            $input['slot_name'],
            $input['start_time'],
            $input['end_time'],
            $input['max_visitors'],
            $input['sort_order'] ?? 1,
            $input['is_active'] ?? 1,
            $input['id']
        ]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode([
                'code' => 200,
                'message' => '时段更新成功'
            ]);
        } else {
            echo json_encode(['code' => 404, 'message' => '时段不存在']);
        }
        
    } catch (Exception $e) {
        echo json_encode(['code' => 500, 'message' => '更新时段失败: ' . $e->getMessage()]);
    }
}

function deleteTimeSlot() {
    // 检查权限
    if (!hasPermission('timeslots.edit')) {
        echo json_encode(['code' => 403, 'message' => '权限不足']);
        return;
    }
    
    $id = $_GET['id'] ?? 0;
    
    if (!$id) {
        echo json_encode(['code' => 400, 'message' => '参数错误']);
        return;
    }
    
    try {
        // 检查是否有预约使用此时段
        $stmt = $GLOBALS['pdo']->prepare("
            SELECT COUNT(*) FROM reservations WHERE time_slot_id = ?
        ");
        $stmt->execute([$id]);
        $count = $stmt->fetchColumn();
        
        if ($count > 0) {
            echo json_encode(['code' => 400, 'message' => '该时段已有预约，无法删除']);
            return;
        }
        
        $stmt = $GLOBALS['pdo']->prepare("DELETE FROM museum_time_slots WHERE id = ?");
        $stmt->execute([$id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode([
                'code' => 200,
                'message' => '时段删除成功'
            ]);
        } else {
            echo json_encode(['code' => 404, 'message' => '时段不存在']);
        }
        
    } catch (Exception $e) {
        echo json_encode(['code' => 500, 'message' => '删除时段失败: ' . $e->getMessage()]);
    }
}

function toggleStatus() {
    // 检查权限
    if (!hasPermission('timeslots.edit')) {
        echo json_encode(['code' => 403, 'message' => '权限不足']);
        return;
    }
    
    $id = $_GET['id'] ?? 0;
    
    if (!$id) {
        echo json_encode(['code' => 400, 'message' => '参数错误']);
        return;
    }
    
    try {
        $stmt = $GLOBALS['pdo']->prepare("
            UPDATE museum_time_slots 
            SET is_active = 1 - is_active, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ");
        $stmt->execute([$id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode([
                'code' => 200,
                'message' => '状态更新成功'
            ]);
        } else {
            echo json_encode(['code' => 404, 'message' => '时段不存在']);
        }
        
    } catch (Exception $e) {
        echo json_encode(['code' => 500, 'message' => '更新状态失败: ' . $e->getMessage()]);
    }
}

function hasPermission($permission) {
    // 简化权限检查，实际应该根据用户角色检查
    return true;
}
?>